<template>
  <div class="xtx-cart-page">
    <div class="container">
      <!-- 面包屑 -->
      <XtxBread>
        <XtxBreadItem to="/"></XtxBreadItem>
        <XtxBreadItem>购物车</XtxBreadItem>
      </XtxBread>

      <div class="cart">
        <table>
          <thead>
          <tr>
            <th width="120">
              <!-- 注意这里不能使用v-model使用双向绑定, 改变vuex的state需要通过提交mutation -->
              <!-- 所以vuex的数据, 不能使用双向数据绑定, 都需要通过mutation来改变 -->
              <XtxCheckbox :modelValue="isCheckAll" @change="checkAll">全选</XtxCheckbox>
            </th>
            <th width="400">商品信息</th>
            <th width="220">单价</th>
            <th width="180">数量</th>
            <th width="180">小计</th>
            <th width="140">操作</th>
          </tr>
          </thead>

          <!-- 有效商品 -->
          <tbody>
          <tr v-if="validList.length === 0">
            <!-- colspan="6" 合并六列 -->
            <td colspan="6">
              <CartNone></CartNone>
            </td>
          </tr>
          <tr v-for="item in validList" :key="item.skuId">
            <td>
              <!--<XtxCheckbox v-model="item.selected"/>-->
              <XtxCheckbox :modelValue="item.selected" @change="checkOne(item.skuId, $event)"/>
            </td>
            <td>
              <div class="goods">
                <router-link :to="`/product/${item.id}`">
                  <img v-lazy="item.picture" alt="">
                </router-link>
                <div>
                  <p class="name ellipsis">{{ item.name }}</p>
                  <!-- 选择规格组件 -->
                  <CartSku :attrsText="item.attrsText"
                           :sku-id="item.skuId"
                           @change="updateCartSku(item.skuId, $event)"></CartSku>
                </div>
              </div>
            </td>
            <td class="tc">
              <p>¥{{ item.nowPrice }}</p>
              <p v-if="item.price -item.nowPrice > 0">
                比加入时降价<span class="red">¥{{ item.price - item.nowPrice }}</span>
              </p>
            </td>
            <td class="tc">
              <!--<XtxNumber v-model:num="item.count"></XtxNumber>-->
              <!-- todo : 使用这个组件要注意最大值的情况 -->
              <XtxNumber :max="item.stock" :num="item.count" @change="changeNum(item.skuId, $event)"></XtxNumber>
            </td>
            <td class="tc">
              <!-- 小计 -->
              <p class="f16 red">
                &yen;{{ Math.round(item.nowPrice * 100) * item.count / 100 }}
              </p>
            </td>
            <td class="tc">
              <p><a href="javascript:;">移入收藏夹</a></p>
              <p><a class="green" href="javascript:;" @click="deleteCart(item.skuId)">删除</a></p>
              <p><a href="javascript:;">找相似</a></p>
            </td>
          </tr>
          </tbody>

          <!-- 无效商品 -->
          <tbody v-if="invalidList.length > 0">
          <tr>
            <td colspan="6">
              <h3 class="tit">失效商品</h3>
            </td>
          </tr>
          <tr v-for="item in invalidList" :key="item.skuId">
            <td>
              <!-- 无效的商品不能选???, 所以不需要传值?? -->
              <XtxCheckbox style="color:#eee;"></XtxCheckbox>
            </td>
            <td>
              <div class="goods">
                <router-link :to="`/product/${item.id}`">
                  <img v-lazy="item.picture" alt="">
                </router-link>
                <div>
                  <p class="name ellipsis">{{ item.name }}</p>
                  <p class="attr">{{ item.attrsText }}</p>
                </div>
              </div>
            </td>
            <td class="tc"><p>&yen;{{ item.nowPrice }}</p></td>
            <td class="tc">{{ item.count }}</td>
            <td class="tc">
              <!-- 小计 -->
              <p>&yen;{{ Math.round(item.nowPrice * 100) * item.count / 100 }}</p>
            </td>
            <td class="tc">
              <p><a class="green" href="javascript:;" @click="deleteCart(item.skuId)">删除</a></p>
              <p><a href="javascript:;">找相似</a></p>
            </td>
          </tr>
          </tbody>
        </table>
      </div>

      <!-- 操作栏 -->
      <div class="action">
        <div class="batch">
          <XtxCheckbox :modelValue="isCheckAll" @change="checkAll">全选</XtxCheckbox>
          <a href="javascript:;" @click="batchDeleteCart(false)">删除商品</a>
          <a href="javascript:;">移入收藏夹</a>
          <a href="javascript:;" @click="batchDeleteCart(true)">清空失效商品</a>
        </div>
        <div class="total">
          共{{ validTotal }}件商品，已选择{{ selectedTotal }}件，商品合计：<span class="red">¥{{ selectedPrice }}</span>
          <XtxButton type="primary" @click="checkout">下单结算</XtxButton>
        </div>
      </div>

      <!-- 猜你喜欢 -->
      <GoodsRelevant></GoodsRelevant>
    </div>
  </div>
</template>

<script>

import GoodsRelevant from '@/components/goods/GoodsRelevant'
import { useStore } from 'vuex'
import { computed } from 'vue'
import Message from '@/components/library/Message'
import CartNone from '@/components/cart/CartNone'
import Confirm from '@/components/library/Confirm'
import CartSku from '@/components/cart/CartSku'
import { useRouter } from 'vue-router'

export default {
  name: 'index',
  components: {
    CartSku,
    CartNone,
    GoodsRelevant
  },
  setup() {
    const store = useStore()
    const router = useRouter()

    // 全选和取消全选处理
    const checkAll = (selected) => {
      // 需要通过mutation来修改state数据, 不能直接修改state
      store.dispatch('cart/checkAllCart', selected)
    }
    // 每个商品的单选框处理
    const checkOne = (skuId, selected) => {
      store.dispatch('cart/updateCart', {
        skuId,
        selected
      })
    }

    // 删除购物车
    const deleteCart = (skuId) => {
      Confirm({ text: '亲, 您是否确认删除该商品' })
          .then(() => {
            store.dispatch('cart/deleteCart', skuId)
                .then(() => {
                  Message({
                    type: 'success',
                    text: '删除成功'
                  })
                })
          })
    }

    // 批量删除选中购物车, 也支持清空无效商品  true为清空无效商品
    const batchDeleteCart = (isClear) => {
      // 健壮性判断
      if (store.getters['cart/selectedList'].length === 0 && !isClear) {
        return Message({ text: '亲, 请您选中商品哦' })
      } else if (store.getters['cart/invalidList'].length === 0 && isClear) {
        return Message({ text: '亲, 你没有失效商品哦' })
      }
      Confirm({ text: `亲, 您是否确认删除${isClear ? '失效' : '选中'}的商品` })
          .then(() => {
            store.dispatch('cart/batchDeleteCart', isClear)
                .then(() => {
                  Message({
                    type: 'success',
                    text: '删除成功'
                  })
                })
          })
    }

    // 修改购物车的数量
    const changeNum = (skuId, count) => {
      store.dispatch('cart/updateCart', {
        skuId,
        count
      })
    }

    /**
     * 修改购物车的sku规格信息
     * @param oldSkuId    改变之前的skuId
     * @param newSkuInfo  改变后部分sku信息
     */
    const updateCartSku = (oldSkuId, newSkuInfo) => {
      //
      store.dispatch('cart/updateCartSku', {
        oldSkuId,
        newSkuInfo
      })
    }

    // 结算
    const checkout = () => {
      // 1.判断是否选中商品, 且提示, 请至少选择一件商品
      if (store.getters['cart/selectedList'].length === 0) {
        return Message({ text: '亲, 请至少选择一件商品' })
      }

      // todo 登录情况不弹出这个提示框 11.34
      if (store.state.user.profile.token) {
        router.push('/member/checkout')
      } else {
        // 2.弹出确认框, 提示:下单结算需要登录
        Confirm({ text: '下单结算需要登录, 确认现在去登录吗?' })
            .then(() => {
              router.push('/member/checkout')
            })
            .catch(() => {
            })
      }

    }

    return {
      invalidList: computed(() => store.getters['cart/invalidList']),
      validList: computed(() => store.getters['cart/validList']),
      validTotal: computed(() => store.getters['cart/validTotal']),
      selectedList: computed(() => store.getters['cart/selectedList']),
      selectedTotal: computed(() => store.getters['cart/selectedTotal']),
      selectedPrice: computed(() => store.getters['cart/selectedPrice']),
      isCheckAll: computed(() => store.getters['cart/isCheckAll']),
      checkAll,
      checkOne,
      deleteCart,
      batchDeleteCart,
      changeNum,
      updateCartSku,
      checkout
    }
  }
}
</script>

<style lang="less" scoped>
.tc {
  text-align: center;

  .xtx-number {
    margin: 0 auto;
    width: 120px;
  }
}

.red {
  color: @priceColor;
}

.green {
  color: @xtxColor;
}

.f16 {
  font-size: 16px;
}

.goods {
  display: flex;
  align-items: center;

  img {
    width: 100px;
    height: 100px;
  }

  > div {
    width: 280px;
    padding-left: 10px;
    font-size: 16px;

    .attr {
      font-size: 14px;
      color: #999;
    }
  }
}

.tit {
  color: #666;
  font-size: 16px;
  font-weight: 400;
  line-height: 50px;
}


.xtx-cart-page {
  .cart {
    background-color: #fff;
    color: #666;

    table {
      border-spacing: 0;
      border-collapse: collapse;
      line-height: 24px;

      // th与td共有的样式
      th, td {
        padding: 10px;
        border-bottom: 1px solid #f5f5f5;

        &:first-child {
          text-align: left;
          padding-left: 30px;
          color: #999;
        }
      }

      // th单独有的样式
      th {
        font-size: 16px;
        font-weight: normal;
        line-height: 50px;
      }
    }

  }

  .action {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 20px 0;
    height: 80px;
    padding: 0 30px;

    background-color: #fff;
    font-size: 16px;

    .xtx-checkbox {
      color: #999;
    }

    .batch {
      a {
        padding-left: 20px;
      }
    }

    .total {
      span {
        margin-right: 20px;
        font-weight: 700;
        font-size: 18px;
      }
    }
  }
}
</style>
